import random
from collections import Counter
from datetime import datetime

from django.conf import settings
from django.db.models import Sum, F
from rest_framework import serializers

from apps.survey_system.question.models import Swiper, Module, ModuleTeam
from apps.survey_system.survey.models import Survey, SurveyAccount, SurveyQuestion, SurveyQuestionOption, SurveyAnswer
from utils.data_dict import get_data_dict


class SurveySerializer(serializers.ModelSerializer):
    updated_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S', label='修改时间', read_only=True)
    display_score_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S', label='显示分数时间', read_only=True)
    start_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S', label='开始时间', read_only=True)
    end_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S', label='结束时间', read_only=True)

    def to_representation(self, instance):
        ret = super().to_representation(instance)
        survey_account_count = self.context.get('survey_account_count', {})
        survey_question_count = self.context.get('survey_question_count', {})
        ret['account_count'] = survey_account_count.get(instance.id, 0)
        ret['question_count'] = survey_question_count.get(instance.id, 0)
        now_datetime = datetime.now()
        if now_datetime >= instance.end_time:
            ret['status'] = '已结束'
        elif now_datetime < instance.start_time:
            ret['status'] = '未开始'
        else:
            ret['status'] = '测评中'

        ret['module_name'] = instance.module.name

        score_dict = get_data_dict('score_type', default_value={})
        ret['score_type'] = score_dict.get(instance.display_score_type, 'None')


        # 随机返回一张图片
        key=random.randint(1, 50)
        ret['photo'] = f'{settings.FILE_URL}survey_system/survey_img/{key}.jpg'

        return ret

    class Meta:
        model = Survey
        fields = '__all__'


# class SurveyAccountSerializer(serializers.ModelSerializer):
#     start_time = serializers.DateTimeField(source='survey.start_time', format='%Y-%m-%d %H:%M:%S', label='开始时间', read_only=True)
#     end_time = serializers.DateTimeField(source='survey.end_time', format='%Y-%m-%d %H:%M:%S', label='结束时间', read_only=True)
#     survey_name = serializers.CharField(source='survey.name')
#     desc = serializers.CharField(source='survey.desc')
#
#     def to_representation(self, instance):
#         ret = super().to_representation(instance)
#         # 返回填写状态
#         status_dict = get_data_dict('survey_status', default_value={})
#         ret['write_status'] = status_dict.get(instance.status, 'None')
#
#         start_time = datetime.strptime(ret['start_time'], "%Y-%m-%d %H:%M:%S")
#         end_time = datetime.strptime(ret['end_time'], "%Y-%m-%d %H:%M:%S")
#         now_datetime = datetime.now()
#         if now_datetime >= end_time:
#             ret['survey_status'] = '已结束'
#         elif now_datetime < start_time:
#             ret['survey_status'] = '未开始'
#         else:
#             ret['survey_status'] = '测评中'
#         return ret
#
#     class Meta:
#         model = SurveyAccount
#         fields = "__all__"


class SurveyAccountSerializer(serializers.ModelSerializer):
    start_time = serializers.DateTimeField(source='survey.start_time', format='%Y-%m-%d %H:%M:%S', label='开始时间',
                                           read_only=True)
    end_time = serializers.DateTimeField(source='survey.end_time', format='%Y-%m-%d %H:%M:%S', label='结束时间',
                                         read_only=True)
    last_submit_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S', label='最后提交时间', read_only=True)
    survey_name = serializers.CharField(source='survey.name', label='调查问卷名', read_only=True)
    display_score_type = serializers.IntegerField(source='survey.display_score_type', label='调查问卷名', read_only=True)
    display_score_time = serializers.DateTimeField(source='survey.display_score_time', format='%Y-%m-%d %H:%M:%S',
                                           label='分数展示时间', read_only=True)
    desc = serializers.CharField(source='survey.desc')

    def to_representation(self, instance):
        ret = super().to_representation(instance)
        survey_account_count = self.context.get('survey_account_count', {})
        survey_question_count = self.context.get('survey_question_count', {})
        ret['account_count'] = survey_account_count.get(instance.id, 0)
        ret['question_count'] = survey_question_count.get(instance.id, 0)

        # 返回填写状态
        status_dict = get_data_dict('survey_status', default_value={})
        ret['write_status'] = status_dict.get(instance.status, 'None')

        # 返回问卷状态
        start_time = datetime.strptime(ret['start_time'], "%Y-%m-%d %H:%M:%S")
        end_time = datetime.strptime(ret['end_time'], "%Y-%m-%d %H:%M:%S")
        now_datetime = datetime.now()
        if now_datetime >= end_time:
            ret['survey_status'] = '已结束'
        elif now_datetime < start_time:
            ret['survey_status'] = '未开始'
        else:
            ret['survey_status'] = '测评中'

        # 返回问卷给分状态
        if ret['display_score_type'] == 1:
            ret['score_status'] = 1
        elif ret['display_score_type'] == 2:
            if now_datetime >= end_time:
                ret['score_status'] = 1
            else:
                ret['score_status'] = 0
        elif ret['display_score_type'] == 3:
            display_score_time = datetime.strptime(ret['display_score_time'], "%Y-%m-%d %H:%M:%S")
            if now_datetime >= display_score_time:
                ret['score_status'] = 1
            else:
                ret['score_status'] = 0
        if ret['score_status'] == 1:
            all_score = SurveyAnswer.objects.filter(survey_account=instance).aggregate(Sum('score'))['score__sum']
            if all_score:
               ret['all_score'] = all_score
            else:
               ret['all_score'] = 0

        # 随机返回一张图片
        key = random.randint(1, 50)
        ret['photo'] = f'{settings.FILE_URL}survey_system/survey_img/{key}.jpg'

        return ret

    class Meta:
        model = SurveyAccount
        fields = "__all__"


class FinishedSurveyAccountSerializer(serializers.ModelSerializer):
    start_time = serializers.DateTimeField(source='survey.start_time', format='%Y-%m-%d %H:%M:%S', label='开始时间',
                                           read_only=True)
    end_time = serializers.DateTimeField(source='survey.end_time', format='%Y-%m-%d %H:%M:%S', label='结束时间',
                                         read_only=True)
    survey_name = serializers.CharField(source='survey.name', label='调查问卷名', read_only=True)
    display_score_type = serializers.IntegerField(source='survey.display_score_type', label='调查问卷名', read_only=True)
    display_score_time = serializers.DateTimeField(source='survey.display_score_time', format='%Y-%m-%d %H:%M:%S',
                                           label='分数展示时间', read_only=True)
    desc = serializers.CharField(source='survey.desc')

    def to_representation(self, instance):
        ret = super().to_representation(instance)
        # 返回填写状态
        status_dict = get_data_dict('survey_status', default_value={})
        ret['write_status'] = status_dict.get(instance.status, 'None')

        # 返回问卷状态
        start_time = datetime.strptime(ret['start_time'], "%Y-%m-%d %H:%M:%S")
        end_time = datetime.strptime(ret['end_time'], "%Y-%m-%d %H:%M:%S")
        now_datetime = datetime.now()
        if now_datetime >= end_time:
            ret['survey_status'] = '已结束'
        elif now_datetime < start_time:
            ret['survey_status'] = '未开始'
        else:
            ret['survey_status'] = '测评中'

        # 返回问卷给分状态
        if ret['display_score_type'] == 1:
            ret['score_status'] = 1
        elif ret['display_score_type'] == 2:
            if now_datetime >= end_time:
                ret['score_status'] = 1
            else:
                ret['score_status'] = 0
        elif ret['display_score_type'] == 3:
            display_score_time = datetime.strptime(ret['display_score_time'], "%Y-%m-%d %H:%M:%S")
            if now_datetime >= display_score_time:
                ret['score_status'] = 1
            else:
                ret['score_status'] = 0
        if ret['score_status'] == 1:
            all_score = SurveyAnswer.objects.filter(survey_account=instance).aggregate(Sum('score'))['score__sum']
            if all_score:
               ret['all_score'] = all_score
            else:
               ret['all_score'] = 0

        return ret

    class Meta:
        model = SurveyAccount
        fields = "__all__"


class SwiperSerializer(serializers.ModelSerializer):
    created_time = serializers.DateTimeField(format="%Y-%m-%d", required=False, read_only=True)
    updated_time = serializers.DateTimeField(format="%Y-%m-%d", required=False, read_only=True)
    account = serializers.HiddenField(  # 默认为当前创建者
        default=serializers.CurrentUserDefault()
    )

    def to_representation(self, instance):
        ret = super().to_representation(instance)
        ret['author'] = instance.account.realname if instance.account else ''
        ret['full_image_path'] = [{'url': f"{settings.FILE_URL}{file.get('url')}", 'name': file.get('name')}
                                  for file in instance.cover]
        return ret

    class Meta:
        model = Swiper
        fields = '__all__'


class ModuleListSerializer(serializers.ModelSerializer):
    created_time = serializers.DateTimeField(format="%Y-%m-%d", required=False, read_only=True)
    updated_time = serializers.DateTimeField(format="%Y-%m-%d", required=False, read_only=True)

    def to_representation(self, instance):
        ret = super().to_representation(instance)
        ret['full_image_path'] = [{'url': f"{settings.FILE_URL}{file.get('url')}", 'name': file.get('name')}
                                  for file in instance.cover]
        return ret

    class Meta:
        model = Module
        fields = '__all__'


class ModuleRetrieveSerializer(serializers.ModelSerializer):
    created_time = serializers.DateTimeField(format="%Y-%m-%d", required=False, read_only=True)
    updated_time = serializers.DateTimeField(format="%Y-%m-%d", required=False, read_only=True)

    def to_representation(self, instance):
        ret = super().to_representation(instance)
        ret['full_image_path'] = [{'url': f"{settings.FILE_URL}{file.get('url')}", 'name': file.get('name')}
                                  for file in instance.cover]

        survey_qs = Survey.objects.filter(module=instance, is_active=True).order_by('-start_time')

        survey_account_qs = SurveyAccount.objects.filter(survey__in=survey_qs, status__in=[1, 2]) \
            .values_list('survey_id', flat=True)
        survey_account_count = Counter(survey_account_qs)
        survey_question_qs = SurveyQuestion.objects.filter(survey_qs_cate__survey__in=survey_qs) \
            .values_list('survey_qs_cate__survey_id', flat=True)
        survey_question_count = Counter(survey_question_qs)

        serializer = SurveySerializer(survey_qs, many=True, context={'survey_account_count': survey_account_count,
                                                                   'survey_question_count': survey_question_count})

        ret['module_survey'] = serializer.data

        module_team = ModuleTeam.objects.filter(module=instance)\
            .values('introduction', 'photo', realname=F('account__realname'), faculty_title=F('account__faculty_title'))

        for qs in module_team:
            qs['photo_full'] = [{'url': f"{settings.FILE_URL}{file.get('url')}", 'name': file.get('name')}
                                  for file in qs['photo']]

        ret['module_team'] = module_team

        return ret

    class Meta:
        model = Module
        fields = '__all__'